<?php
namespace Models;

require_once('\Models\Image.php');
require_once('\Common\DBTables.php');

class ImageCatalog
{	
	/**
	 * Hämtar en array av bilder
	 * @return $images ImageArray
	 */
	public function getImages(\Models\Database $db, $albumId = "", $selectedImages = array())
	{
		$dbt = new \Common\DBTables();
		
		$sql = "SELECT ".
		$dbt->imageIdField.",".
		$dbt->albumIdField.",".
		$dbt->imageDescriptionField.",".
		$dbt->imageUrlField.",".
		$dbt->thumbUrlField." 
		FROM ".$dbt->imageTable."";
		
		if($albumId != "")
			$sql .= " WHERE ".$dbt->albumIdField."=".$albumId."";
		
		$statement = $db->Select($sql);
		
		// Bind resultat innan vi anropar fetch()
		if ($statement->bind_result($dbt->imageIdField, $dbt->albumIdField, $dbt->imageDescriptionField, $dbt->imageUrlField, $dbt->thumbUrlField) == FALSE)
			throw new \Exception($this->mysqli->error);

	    $images = new \Models\ImageArray();
		
		// Om särskilda bilder ur albumet ska hämtas
    	if(count($selectedImages)>0)
		{
			while ($statement->fetch())
    		{
    			// Om imageId återfinns i $selectedImages
				if(in_array($dbt->imageIdField, $selectedImages))
				{
					$image = new \Models\Image($dbt->imageIdField, $dbt->albumIdField, $dbt->imageDescriptionField, $dbt->imageUrlField, $dbt->thumbUrlField);
					$images->add($image);
				}
			}
		}
		else
		{
			while ($statement->fetch())
			{
				$image = new \Models\Image($dbt->imageIdField, $dbt->albumIdField, $dbt->imageDescriptionField, $dbt->imageUrlField, $dbt->thumbUrlField);
				$images->add($image);
			}
		}
		
		$statement->close();
		
		if(count($images->get()) == 0)
			return false;
		else
			return $images;
	}
	
	/**
	 * Hämtar en bild
	 * @return $image Image
	 */
	public static function getImage(\Models\Database $db, $imageId)
	{
		$dbt = new \Common\DBTables();
		
		$sql = "SELECT ".
		$dbt->imageIdField.",".
		$dbt->albumIdField.",".
		$dbt->imageDescriptionField.",".
		$dbt->imageUrlField.",".
		$dbt->thumbUrlField." 
		FROM ".$dbt->imageTable."
		WHERE ".$dbt->imageIdField."=".$imageId."";
		
		$statement = $db->Select($sql);
		
		// Bind resultat innan vi anropar fetch()
		if ($statement->bind_result($dbt->imageIdField, $dbt->albumIdField, $dbt->imageDescriptionField, $dbt->imageUrlField, $dbt->thumbUrlField) == FALSE)
			throw new \Exception($this->mysqli->error);
		
	    if($statement->fetch())
	        $image = new \Models\Image($dbt->imageIdField, $dbt->albumIdField, $dbt->imageDescriptionField, $dbt->imageUrlField, $dbt->thumbUrlField);
		else
			return null;
		
		$statement->close();
		
		return $image;
	}
}

?>